import requests
import json
import GetTime
import ReturnFake
import WriteIntoDB
import WriteIntoExcel


class GetNews:
    def __init__(self):
        self.num = 1
        self.contents = []

    # worksheet是每个组织的sheet页面，orgid是每个组织的id
    def write(self, obj, dayNews, worksheet, orgid):
        for index in range(1, 100):
            # 每个组织的活动链接
            url = '''https://api.12355.net/activity/publisher/activitiesList?orgId=''' + orgid \
                  + '''&pageIndex=''' + str(index) + '''&pageSize=10'''
            # 使用requests库的get方法，返回一个response对象，并设置超时时间和User-Agent以及代理IP
            response = requests.get(url, timeout=120, headers=ReturnFake.getAgent())  # ,proxies=getProxy()
            # 设置解码格式
            response.encoding = 'utf-8'
            # 抛出错误请求异常
            response.raise_for_status()
            # 获取解码后的数据
            html_json = response.text
            # 使用json库的loads方法进行解析
            data = json.loads(html_json)
            # 如果页面没有内容，停止当前循环
            if len(data['rows']) == 0:
                break
            # 循环的次数为每一页的活动数
            for i in range(len(data['rows'])):
                # 获取活动创建时间
                time = (data['rows'][i]['createTime'].strip()).split('-')
                year = time[0]
                mouth = time[1]
                # 设置只爬取本月的活动
                if year == GetTime.getYear() and mouth == GetTime.getMouth():
                    print('第', str(self.num), '个活动', sep='')
                    self.num = self.num + 1
                    # 活动id
                    activityId = data['rows'][i]['id']
                    # 活动名称
                    title = data['rows'][i]['title']
                    # 活动时间
                    activityTime = data['rows'][i]['activityTime']
                    # 创建时间
                    createTime = data['rows'][i]['createTime']
                    # 主办方
                    address = data['rows'][i]['address']
                    # 活动图片链接
                    imageUrl = data['rows'][i]['imageUrl']
                    # 活动链接
                    activityUrl = '''https://www.12355.net/pc/view/find_active/zhd_xiangqing.html?activityId=''' \
                                  + str(activityId)
                    print('活动标题：', title)
                    print('活动时间：', activityTime)
                    print('活动地址：', address)
                    print('图片：', imageUrl)
                    print('网址：', activityUrl)
                    print('======================================')

                    # 下载活动图片
                    try:
                        img = requests.get(imageUrl).content
                        with open('image/'+title+'.jpg','wb') as f:
                            f.write(img)
                    except IOError as e:
                        print("IO ERROR")
                    except Exception as e:
                        print("Exception")
                    # 将获取到的数据存储进content数组
                    content = [activityId, title, createTime, activityTime, address, imageUrl, activityUrl]
                    # 将content数组添加到contents数组中
                    self.contents.append(content)
                    # 写入txt
                    day = time[2].split(' ')
                    day = day[0]
                    activityStartTime = activityTime.split('--')
                    activityStartTime = activityStartTime[0].split('.')
                    activityStartTime = activityStartTime[2]
                    content = [
                        '活动数：', str(self.num - 1), '\n',
                        '活动Id：', str(activityId), '\n',
                        '活动标题：', str(title), '\n',
                        '创建时间：', str(createTime), '\n',
                        '活动时间：', str(activityTime), '\n',
                        '活动地址：', str(address), '\n',
                        '图片链接：', str(imageUrl), '\n',
                        '活动链接：', str(activityUrl), '\n\n']

                    content1 = [
                        '名称：', str(title), '\n',
                        '时间：', str(activityTime), '\n',
                        '链接：', str(activityUrl), '\n\n']
                    # 写入当天活动
                    if (day == GetTime.getDay() or int(day) == int(GetTime.getDay())-1
                        or int(day) == int(GetTime.getDay())-2) and (int(activityStartTime) >= int(GetTime.getDay())):
                        dayNews.writelines(content1)
                    # 写入当月活动
                    if day != GetTime.getDay() or day == GetTime.getDay():
                        obj.writelines(content)
                    # 写入数据库
                    WriteIntoDB.writeToMyDB(activityId, title, createTime, activityTime, address, imageUrl, activityUrl)
        # 写入excel
        news = self.contents
        if len(news) != 0:
            WriteIntoExcel.writeToMyExcel(worksheet, news)

    def setNull(self):
        # 将爬取到的当前组织活动数组设置为空，以便下一个组织存储
        self.contents = []